<template>
  <div class="brands-container">
    <div class="filter-container">
      <el-input
        v-model="listQuery.name"
        placeholder="品牌名称"
        prefix-icon="el-icon-shopping-bag-1"
        clearable
        class="filter-item"
        @keyup.enter.native="handleFilter"
      />
      <el-button class="filter-item" type="primary" icon="el-icon-search" @click="handleFilter">
        搜索
      </el-button>
      <el-button class="filter-item add-button" type="success" icon="el-icon-plus" @click="handleCreate">
        添加品牌
      </el-button>
    </div>

    <el-table
      v-loading="listLoading"
      :data="list"
      element-loading-text="加载中..."
      border
      fit
      highlight-current-row
      style="width: 100%"
    >
      <el-table-column label="ID" width="80" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.id }}</span>
        </template>
      </el-table-column>

      <el-table-column label="品牌名称" min-width="200" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.name }}</span>
        </template>
      </el-table-column>

      <el-table-column label="品牌图片" min-width="150" align="center">
        <template slot-scope="scope">
          <img v-if="scope.row.logo" :src="'http://localhost:8080/api' + scope.row.logo" alt="品牌图片" style="height: 50px;">
          <span v-else>无图片</span>
        </template>
      </el-table-column>

      <el-table-column label="描述" min-width="200" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.description }}</span>
        </template>
      </el-table-column>

      <el-table-column label="创建时间" min-width="180" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.createTime }}</span>
        </template>
      </el-table-column>

      <el-table-column label="操作" min-width="180" align="center" fixed="right">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="primary"
            @click="handleUpdate(scope.row)"
          >
            编辑
          </el-button>
          <el-button
            size="mini"
            type="danger"
            @click="handleDelete(scope.row)"
          >
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <div class="pagination-container">
      <el-pagination
        background
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="listQuery.page"
        :page-sizes="[10, 20, 30, 50]"
        :page-size="listQuery.limit"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      />
    </div>

    <!-- 品牌表单对话框 -->
    <el-dialog :title="dialogStatus === 'create' ? '添加品牌' : '编辑品牌'" :visible.sync="dialogFormVisible">
      <el-form ref="dataForm" :model="temp" :rules="rules" label-width="100px" style="width: 400px; margin: 0 auto;">
        <el-form-item label="品牌名称" prop="name">
          <el-input v-model="temp.name" />
        </el-form-item>
        <el-form-item label="品牌图片">
          <el-upload
            class="avatar-uploader"
            action="http://localhost:8080/api/waterBrand/upload"
            :headers="uploadHeaders"
            :show-file-list="false"
            :on-success="handleUploadSuccess"
            :before-upload="beforeUpload"
            :with-credentials="true"
          >
            <img v-if="temp.logo" :src="'http://localhost:8080/api' + temp.logo" class="avatar">
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
            <div class="el-upload__tip" slot="tip">只能上传jpg/png文件，且不超过2MB</div>
          </el-upload>
        </el-form-item>
        <el-form-item label="描述" prop="description">
          <el-input v-model="temp.description" type="textarea" :rows="3" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取消</el-button>
        <el-button type="primary" @click="dialogStatus === 'create' ? createData() : updateData()">确认</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { getBrandList, addBrand, updateBrand, deleteBrand } from '@/api/brand'

export default {
  name: 'Brands',
  data() {
    return {
      list: [],
      total: 0,
      listLoading: true,
      listQuery: {
        page: 1,
        limit: 10,
        name: undefined
      },
      temp: {
        id: undefined,
        name: '',
        logo: '',
        description: ''
      },
      dialogFormVisible: false,
      dialogStatus: '',
      uploadHeaders: {
        Authorization: 'Bearer ' + localStorage.getItem('token')
      },
      rules: {
        name: [{ required: true, message: '请输入品牌名称', trigger: 'blur' }],
        description: [{ required: true, message: '请输入品牌描述', trigger: 'blur' }]
      }
    }
  },
  created() {
    this.getList()
  },
  methods: {
    getList() {
      this.listLoading = true
      
      // 构建查询参数
      const params = {
        current: this.listQuery.page,
        size: this.listQuery.limit,
        keyword: this.listQuery.name
      }
      
      getBrandList(params).then(response => {
        this.list = response.data.records
        this.total = response.data.total
        this.listLoading = false
      })
    },
    handleFilter() {
      this.listQuery.page = 1
      this.getList()
    },
    handleSizeChange(val) {
      this.listQuery.limit = val
      this.getList()
    },
    handleCurrentChange(val) {
      this.listQuery.page = val
      this.getList()
    },
    resetTemp() {
      this.temp = {
        id: undefined,
        name: '',
        logo: '',
        description: ''
      }
    },
    handleCreate() {
      this.resetTemp()
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    createData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          addBrand(this.temp).then(() => {
            this.dialogFormVisible = false
            this.$message({
              message: '创建成功',
              type: 'success',
              duration: 2000
            })
            this.getList()
          })
        }
      })
    },
    handleUpdate(row) {
      this.temp = Object.assign({}, row) // 复制一份，避免直接修改原数据
      this.dialogStatus = 'update'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    updateData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          const tempData = Object.assign({}, this.temp)
          updateBrand(tempData).then(() => {
            this.dialogFormVisible = false
            this.$message({
              message: '更新成功',
              type: 'success',
              duration: 2000
            })
            this.getList()
          })
        }
      })
    },
    handleDelete(row) {
      this.$confirm('确认删除该品牌吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        deleteBrand(row.id).then(() => {
          this.$message({
            message: '删除成功',
            type: 'success',
            duration: 2000
          })
          this.getList()
        })
      }).catch(() => {})
    },
    beforeUpload(file) {
      const isJPG = file.type === 'image/jpeg' || file.type === 'image/png'
      const isLt2M = file.size / 1024 / 1024 < 2

      if (!isJPG) {
        this.$message.error('上传图片只能是 JPG 或 PNG 格式!')
      }
      if (!isLt2M) {
        this.$message.error('上传图片大小不能超过 2MB!')
      }
      return isJPG && isLt2M
    },
    handleUploadSuccess(res, file) {
      if (res.code === 200) {
        this.temp.logo = res.data
        this.$message.success('上传成功')
      } else {
        this.$message.error('上传失败: ' + (res.message || '未知错误'))
      }
    }
  },
  beforeRouteEnter(to, from, next) {
    const userRole = localStorage.getItem('userRole')
    if ((userRole || '').toLowerCase() !== 'admin') {
      next('/404')
    } else {
      next()
    }
  }
}
</script>

<style scoped>
.brands-container {
  padding: 30px;
  background-color: #f5f7fa;
  min-height: calc(100vh - 84px);
}

.filter-container {
  display: flex;
  align-items: center;
  margin-bottom: 25px;
  padding: 15px;
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
}

.filter-item {
  margin-right: 15px;
}

.pagination-container {
  margin-top: 25px;
  text-align: center;
  background-color: #fff;
  padding: 15px;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
}

.el-table {
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
  table-layout: fixed;
}

.el-table__body {
  width: 100% !important;
}

.el-button--primary {
  background-color: #409EFF;
  border-color: #409EFF;
  padding: 10px 20px;
}

.el-button--success {
  background-color: #67C23A;
  border-color: #67C23A;
  padding: 10px 20px;
}

.el-button--danger {
  background-color: #F56C6C;
  border-color: #F56C6C;
}

.add-button {
  margin-left: auto;
}

.el-input {
  width: 220px;
}

.el-tag {
  padding: 5px 10px;
}

.el-dialog__body {
  padding: 20px 30px;
}

.el-form-item {
  margin-bottom: 22px;
}

.dialog-footer {
  text-align: right;
  margin-top: 10px;
}

.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}

.avatar-uploader .el-upload:hover {
  border-color: #409EFF;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}

.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>
